package com.ts.api.module.channel.service.impl;

import com.gitee.apanlh.util.cache.redis.RedisKeyBuilder;
import com.gitee.apanlh.util.cache.redis.api.RedisString;
import com.gitee.apanlh.util.random.RandomUtils;
import com.ts.api.common.context.ChannelContext;
import com.ts.api.common.context.ChannelUserContext;
import com.ts.api.module.channel.service.ChannelResetFlowService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 重置流程，如果今天24点之前没有跟踪用户任何操作则检查时返回true
 *
 * @author caoxin
 */
@Service
@Slf4j
public class ChannelResetFlowServiceImpl implements ChannelResetFlowService {

    private static final RedisString REDIS = RedisKeyBuilder.builder().withKeys("channel_token_reset_flow").buildString();

    /**
     * 跟踪
     */
    @Override
    public void track() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 获取明天的0点（下一个午夜）
        LocalDateTime nextMidnight = LocalDate.now().plusDays(1).atStartOfDay();
        // 计算时间差（秒）
        long seconds = Duration.between(now, nextMidnight).getSeconds();
        // 随机数0~600，避免redis在同一秒过期太多的key
        long randomLong = RandomUtils.randomLong(600);

        String unicode = ChannelContext.getUnicode();
        String phone = ChannelUserContext.get().getPhone();
        String key = unicode + ":" + phone;
        try {
            // 保存
            REDIS.setForSeconds(key, "1", seconds + randomLong);
        } catch (Exception e) {
            log.error("操作redis失败", e);
        }
    }

    /**
     * 检查
     *
     * @return 检查结果
     */
    @Override
    public Boolean check() {
        String unicode = ChannelContext.getUnicode();
        String phone = ChannelUserContext.get().getPhone();
        String key = unicode + ":" + phone;
        // 存在则返回false
        boolean exist = REDIS.exist(key);
        if (exist) {
            return false;
        }
        return true;
    }

}
